'use strict';

// 通过 require 引入 vk 实例
const vk = require('vk-unicloud');
const crypto = require('crypto');
const db = uniCloud.database();
const _ = db.command;
// 通过 vk.init 初始化 vk实例（只有初始化后才能使用）
vk.init({
	baseDir: __dirname,
	requireFn: require
});

exports.main = async (event, context) => {
	//=====生成快手access_token=====
	let ks_token = await vk.request({
		url: "https://open.kuaishou.com/oauth2/access_token",
		method: "POST",
		header: {
			'content-Type': 'application/x-www-form-urlencoded'
		},
		data: {
			app_id: "ks709035469146647686", //小程序的AppID
			app_secret: "kIX9mZ29Pz16R1ouvR5VyQ", //小程序的AppSecret
			grant_type: "client_credentials"
		}
	});
	var ks_access_token = ks_token.access_token;
	console.log("ks_access_token=", ks_access_token);
	//=====生成快手access_token结束=====


	//=====抖音端支付订单批量结算开始=====
	let dy_orders = await db.collection('a_recharge').where({
		pay_status: 1,
		platform: "tt",
		settle: 0 //代表未结算
	}).limit(500).get()
	console.log("dy_orders=", dy_orders.data);

	var dy_sign_arr = [] //批量执行时需要用到的数组
	let orderlist = [] //存放订单号的数组
	orderlist = vk.pubfn.arrayObjectGetArray(dy_orders.data, "out_trade_no");
	
	// let orderlist = [
	// 	'NO22100517242522752213487',
	// 	'NO22092914420711932272283',
	// 	'NO22092813392647819843269',
	// 	'NO22092813341667547858565',
	// 	'NO22092813290491271546241',
	// 	'NO22092812014674754331537',
	// 	'NO22092720512118152448474',
	// 	'NO22092709535114563698261',
	// ] //存放订单号的数组

	let batchRun_dy = await vk.pubfn.batchRun({
		// 主执行函数
		main: async (item, index) => {
			await vk.pubfn.sleep((Math.floor(Math.random() * (3 - 0)) + 0) * 100);
			dy_settle(item, index)
			return { code: 0, index }
		},
		// 最大并发量，如果设置为1，则会按顺序执行
		concurrency: 1,
		// 数据源，这些数据会依次跑一遍main函数
		data: orderlist,
	});
	//=====抖音端支付订单批量结算结束=====



	//=====快手端支付订单批量结算开始=====
	let ks_orders = await db.collection('a_recharge').where({
		pay_status: 1,
		platform: "ks",
		settle: 0 //代表未结算
	}).limit(500).get()
	var ks_sign_arr = [] //批量执行时需要用到的数组
	let orderlist1 = [] //存放订单号的数组
	orderlist1 = vk.pubfn.arrayObjectGetArray(ks_orders.data, "out_trade_no");
	console.log("orderlist1=", orderlist1);

	let batchRun_ks = await vk.pubfn.batchRun({
		// 主执行函数
		main: async (item, index) => {
			await vk.pubfn.sleep((Math.floor(Math.random() * (3 - 0)) + 0) * 100);
			ks_settle(item, index)
			return { code: 0, index }
		},
		// 最大并发量，如果设置为1，则会按顺序执行
		concurrency: 1,
		// 数据源，这些数据会依次跑一遍main函数
		data: orderlist1,
	});
	//=====快手端支付订单批量结算结束=====

	return event




	//===============自定义函数开始===============

	//===============自定义函数：抖音订单结算开始===============
	async function dy_settle(out_order_no, index) {
		console.log("进入结算流程", out_order_no);
		let SALT = "JJaTUtrKXHgXZJqSTI6BSTjBq4hO8wTLD6wes2WI";
		let params = {
			"app_id": "tt0fe3795e90dd51a301",
			"out_settle_no": out_order_no,
			"out_order_no": out_order_no,
			"thirdparty_id": "",
			"finish": "true",
			"settle_desc": "jiesuan"
		};
		let skip_arr = ["thirdparty_id", "app_id", "sign"];
		let paramArray = new Array();
		for (let k in params) {
			if (skip_arr.indexOf(k) != -1) {
				continue;
			}
			if (params[k] == "") {
				continue;
			}
			paramArray.push(params[k]);
		}
		paramArray.push(SALT);
		paramArray.sort();
		dy_sign_arr[index] = paramArray.join("&");
		// console.log("signStr=", dy_sign_arr[index]);
		let md5 = crypto.createHash('md5');
		dy_sign_arr[index] = md5.update(dy_sign_arr[index]).digest('hex');
		// console.log("signStr_md5=", dy_sign_arr[index]);
		let dy_requestRes = await vk.request({
			url: "https://developer.toutiao.com/api/apps/ecpay/v1/settle",
			method: "POST",
			header: {
				"Content-Type": "application/json"
			},
			data: {
				"app_id": "tt0fe3795e90dd51a301",
				"out_settle_no": out_order_no,
				"out_order_no": out_order_no,
				"thirdparty_id": "",
				"finish": "true",
				"settle_desc": "jiesuan",
				"sign": dy_sign_arr[index],
			},
			useContent: true, // 是否需要将data请求参数转成body请求体
		});
		console.log("dy_requestRes=", dy_requestRes);
		//当返回成功后(err_no=0)，把数据库里的订单settle改为1，标记为已分账
		if (dy_requestRes.err_no == 0) {
			let dy_up_settle = await db.collection('a_recharge').where({
				out_trade_no: out_order_no,
				settle: 0
			}).update({ settle: 1 })
		}
	}
	//===============自定义函数：抖音订单结算结束===============


	//===============自定义函数：快手订单结算开始===============
	async function ks_settle(out_order_no, index) {
		console.log("进入结算流程", out_order_no);
		let aa = "app_id=ks709035469146647686&";
		let bb = "notify_url=https://1415f5c4-7652-4de1-af09-6bd9341cf175.bspapp.com/ks_pay_notify&";
		let cc = "out_order_no=" + out_order_no + "&";
		let dd = "out_settle_no=" + out_order_no + "&";
		let ee = "reason=jiesuan";
		ks_sign_arr[index] = aa + bb + cc + dd + ee + "kIX9mZ29Pz16R1ouvR5VyQ";
		let md5 = crypto.createHash('md5');
		ks_sign_arr[index] = md5.update(ks_sign_arr[index]).digest('hex');

		let ks_requestRes = await vk.request({
			url: "https://open.kuaishou.com/openapi/mp/developer/epay/settle?app_id=ks709035469146647686&access_token=" +
				ks_access_token,
			method: "POST",
			header: {
				"Content-Type": "application/json"
			},
			data: {
				"app_id": "ks709035469146647686",
				"access_token": ks_access_token,
				"out_order_no": out_order_no,
				"out_settle_no": out_order_no,
				"reason": "jiesuan",
				"notify_url": "https://1415f5c4-7652-4de1-af09-6bd9341cf175.bspapp.com/ks_pay_notify",
				"sign": ks_sign_arr[index]
			},
			useContent: true, // 是否需要将data请求参数转成body请求体
		});
		console.log("ks_requestRes=", ks_requestRes);
		//当返回成功后(result=1)，把数据库里的订单settle改为1，标记为已分账
		if (ks_requestRes.result == 1) {
			let ks_up_settle = await db.collection('a_recharge').where({
				out_trade_no: out_order_no,
				settle: 0
			}).update({ settle: 1 })
		}
	}
	//===============自定义函数：快手订单结算结束===============
};
